//
//  FPHomePageController.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/15.
//

#import "FPHomePageController.h"
#import "FPBannerCell.h"
#import "FPHomeHeaderView.h"
#import "FPManualController.h"
#import "FPAuthenticationController.h"
#import "FPNoDataController.h"
#import "FPLoanController.h"
#import "FPHomeModel.h"
#import "FPProfileEditorController.h"
#import "FPHomeFooterView.h"
#import "FPAboutUsController.h"
#import "FPQuotaInreviewController.h"
#import "FPHomeCollectionCell.h"
#import "FPHomeProductCell.h"
#import "FPHomeProductTipCell.h"
#import "FPProductListController.h"
#import "FPMeProfileController.h"
#import "FPHomeBannerModel.h"
#import "FPLoginController.h"
#import "FPRecommonProductController.h"
#import "FPProductModel.h"
#import "FPMeProfileTwoController.h"
#import "FPWebViewVC.h"

@interface FPHomePageController () <UIScrollViewDelegate , UITableViewDelegate , UITableViewDataSource>

@property (nonatomic , strong) FPHomeHeaderView *headerView;
@property (nonatomic , strong) FPHomeFooterView *footerView;
@property (nonatomic , strong) FPHomeModel *model;
@property (nonatomic , assign) BOOL needRefreshData;
@property (nonatomic , assign) BOOL loginInvalidRet;
@property (nonatomic , strong) NSMutableArray *collectionSource;
@property (nonatomic , strong) NSMutableArray *productSource;
@property (nonatomic , strong) NSMutableArray *bannerSource;
@property (nonatomic , strong) NSString *featuredName;

@property (nonatomic , assign) BOOL firstRegister;
@property (nonatomic , assign) BOOL didBorrowed; //!< 已经借过钱了
@end

@implementation FPHomePageController

LazyLoadDataSource(collectionSource);
LazyLoadDataSource(productSource);
LazyLoadDataSource(bannerSource);

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 确保首页显示TabBar
    self.hidesBottomBarWhenPushed = NO;
    
    self.didBorrowed = NO;
    self.view.backgroundColor = MAIN_VIEW_BACKGROUND_COLOR;
    
//    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//    NSLog(@"home page = %@", [defaults valueForKey:PRIVACY_CONTROLLER]);
    
    // 借款成功 首页刷新额度
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getData) name:LoanApplySuccessNotification object:nil];
    // 登录成功 首页刷新额度
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:LoginSuccessNotification object:nil];
    // 登录失效
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginInvalidAction) name:UserTokenInvalidNotification object:nil];
    // 主动退出登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginInvalidAction) name:LogoutNotification object:nil];
    // 留资2完成 刷新
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData:) name:UserProfileCompleteNotification object:nil];
    
    self.needRefreshData = NO;
    self.loginInvalidRet = NO;
}

- (void)refreshData:(NSNotification *)notify {
    
    if ([notify.object isEqualToString:@"1"]) {
    
        self.needRefreshData = YES;
    }
    
    [self getUserInfo];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.needRefreshData) {
        
        self.needRefreshData = NO;
        [self getUserInfo];
    }
    
    if (self.loginInvalidRet) {
        
        self.loginInvalidRet = NO;
        
        [self notLogin];
        [self.tableView reloadData];
    }
}


- (void)toAuthControllerAction {
    
    // 去实名
    FPAuthenticationController *vc = [[FPAuthenticationController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 首页是否弹窗 或者跳实名页面
- (void)getJumpData {
    
    if (FPUserModel.globalToken.length < 1) {
        
        return;
    }
    
    [FPHomeDataModel getJumpDataSuccess:^(NSInteger dataCode, NSString * _Nonnull message, FPHomeDataModel * _Nonnull model) {
        
        if (dataCode == 200) {
            
            // 0:刚注册 1:认证完成 2:留资1完成 3:留资2完成 4:留资完成 没有借款 5:匹配到了 借款了 不用弹 不用跳
            if (model.status.integerValue == 0) {
                
                if (model.jump.boolValue == YES) {
                    
                    // 去实名
                    [self toAuthControllerAction];
                }
            }
            else if (model.status.integerValue == 1) {
                
                if (model.jump.boolValue == YES) {
                 
                    // 留资1没有完成 只认证实名了
                    LXAlertView *alert = [[LXAlertView alloc] initNoticeAlertWithTitleString:@"温馨提示" contentString:@"尊敬的用户您好，系统检测到您为优质用户，已对您进行初审通过，请尽快填写资料进行额度核验。" showBtnCounts:2 btn1:@"暂时不用" btn2:@"去填写" btn3:@"1" alertAlertResult:^(NSInteger index) {
                       
                        // 去借款步骤
                        if (index == 2) {
                            
                            [self toAuthAction];
                        }
                    }];
                    [alert showLXAlertView];
                }
            }
            else if (model.status.integerValue == 2) {
                
                if (model.jump.boolValue == YES) {
                 
                    // 留资1完成 没有留资2
                    LXAlertView *alert = [[LXAlertView alloc] initNoticeAlertWithTitleString:@"温馨提示" contentString:@"尊敬的用户您好，系统检测到您为优质用户，已对您进行初审通过，请尽快填写资料进行额度核验。" showBtnCounts:2 btn1:@"暂时不用" btn2:@"去填写" btn3:@"1" alertAlertResult:^(NSInteger index) {
                       
                        // 去借款步骤
                        if (index == 2) {
                            
                            [self toAuthAction];
                        }
                    }];
                    [alert showLXAlertView];
                }
            }
            else if (model.status.integerValue == 3 || model.status.integerValue == 4) {
                
                if (model.jump.boolValue == YES) {
                 
                    // 留资完成 没有借款
                    NSString *text = [NSString stringWithFormat:@"您的预估可借额度为%@元，为避免额度失效，请您按需完成借款。",self.model.totalCredit.length > 0 ? self.model.totalCredit : @"200000"];
                    LXAlertView *alert = [[LXAlertView alloc] initNoticeAlertWithTitleString:@"温馨提示" contentString:text showBtnCounts:2 btn1:@"暂时不用" btn2:@"去借款" btn3:@"1" alertAlertResult:^(NSInteger index) {
                       
                        // 去借款步骤
                        if (index == 2) {
                            
                            [self toAuthAction];
                        }
                    }];
                    [alert showLXAlertView];
                }
            }
        }
        
    } failure:^(NSError * _Nonnull dataError) {
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    
    [UIViewController popGestureClose:self];
    
    // 确保TabBar可见 - 设置hidesBottomBarWhenPushed为NO
    self.hidesBottomBarWhenPushed = NO;
    
    // 强制刷新TabBar显示
    if (self.tabBarController && self.tabBarController.tabBar) {
        // 确保TabBar不是隐藏状态
        self.tabBarController.tabBar.hidden = NO;
        self.tabBarController.tabBar.alpha = 1.0;
    }
    
    // 埋点
    [FPRecordPointModel recordPointWithChannel:@"8" success:^(NSInteger code, NSString * _Nonnull message) {
    } failure:^(NSError * _Nonnull error) {
    }];
    
    if (FPUserModel.globalToken.length) {
        
        [FPRecordPointModel recordPointWithType:@"5" success:^(NSInteger code, NSString * _Nonnull message) {
        } failure:^(NSError * _Nonnull error) {
        }];
    }
    [self getJumpData];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [UIViewController popGestureOpen:self];
}

- (void)initUI {
    
    [self setTitle:@"" style:(XYCustomNavigationStyleClear) hiddenBackBtn:YES];
    
#warning login
//    self.controllerType = TypeOfHomeOrProfileHome;
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0.f, 0, SCREEN_WIDTH, SCREEN_HEIGHT - UIDevice.tabBarFullHeight);
    
    [self.tableView registerClass:FPHomeCollectionCell.class forCellReuseIdentifier:@"DefaultCell"];
    
    self.tableView.backgroundColor = UIColor.clearColor;
    
    self.headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPHomeHeaderView.class) owner:nil options:nil].lastObject;
    self.tableView.tableHeaderView = self.headerView;
    
    self.footerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPHomeFooterView.class) owner:nil options:nil].lastObject;
    self.tableView.tableFooterView = self.footerView;
    
    [self.footerView.moreLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(aboutUsAction)]];
    
    self.headerView.topToHeight.constant = UIDevice.statusBarHeight + 24.f;
    
//    self.tableView.panGestureRecognizer.delegate = self;
    
    [self.headerView.authTipLab2 addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toAuthAction)]];
    
    [self setReduceHeaderHeight:0.f hideAuthView:YES];
    
    CGFloat footerHeight;
    footerHeight = 151.f / 319.f * (SCREEN_WIDTH - 32.f - 24.f);
    
    self.footerView.frame = CGRectMake(0.f , 0.f, SCREEN_WIDTH, 232.f + footerHeight - 151.f + 150.f);
    
    // 立即申请
    [self.headerView.applyBtn handleViewControlEvents:UIControlEventTouchUpInside withBlock:^{
        
//        FPMeProfileTwoController *vc = [[FPMeProfileTwoController alloc] init];
//        [self.navigationController pushViewController:vc animated:YES];
//        return;
        [self toAuthAction];
    }];
    
    [self getBannerData];
    // 获取用户信息
    [self getUserInfo];
    [self rateDataInfo];
    FPCustomRefreshHeader *refreshHeader = [FPCustomRefreshHeader headerWithRefreshingBlock:^{
        
        // 埋点
        [FPRecordPointModel recordPointWithChannel:@"8" success:^(NSInteger code, NSString * _Nonnull message) {
        } failure:^(NSError * _Nonnull error) {
        }];
        
        [self getBannerData];
        [self rateDataInfo];
        [self getUserInfo];
        [self getFeatureName];
        [self getJumpData];
        
        NSLog(@"token ===============================================================\n%@\n===============================================================",FPUserModel.globalToken);

    }];
    [refreshHeader setActivityColor:UIColor.grayColor];
    refreshHeader.statusLabColor = UIColor.grayColor;
    self.tableView.mj_header = refreshHeader;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self loadCollectionSource];
    
    [self getFeatureName];
    
    if (FPUserModel.firstRegisterUser == YES) {
        
        [self toAuthControllerAction];
        [FPUserModel setFirstRegisterUser:NO];
    }
}

- (void)toAuthAction {
    
    if ([self userIsLogin]) {
        
//            FPMeProfileTwoController *vc = [[FPMeProfileTwoController alloc] init];
//            [self.navigationController pushViewController:vc animated:YES];
//            return;
        [MBManager showLoading];
        [FPUserInfoModel checkUserProfileInfoSuccess:^(NSInteger code, NSString * _Nonnull message , FPUserInfoModel *userInfoModel) {
            
            NSInteger statusCode = userInfoModel.status.integerValue;
            
//            入资状态判断（0未实名，1已实名，2留资1完成，3留资2完成）
            if (statusCode == 0) {
                [MBManager hideLoading];
                FPAuthenticationController *vc = [[FPAuthenticationController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if (statusCode == 1) {
                [MBManager hideLoading];
                FPMeProfileController *vc = [[FPMeProfileController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if (statusCode == 2) {
                [MBManager hideLoading];
                FPMeProfileTwoController *vc = [[FPMeProfileTwoController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            else if (statusCode == 3 || statusCode == 4 || statusCode == 5) {
                NSArray *arrayTestPhones = @[@"13709065567",@"17628247732",@"13548249124"];
                if ([arrayTestPhones containsObject:FPUserInfoModel.sharedUserInfo.phone]) {
                    [MBManager hideLoading];
                    [self showText:@"申请成功，请等待客服电话"];
                }else{
                    [FPUserInfoModel outIdWithParam:@{} success:^(NSString * _Nonnull webUrl, NSString * _Nonnull msg, NSInteger code) {
                        if (code == 200) {
                            [MBManager hideLoading];
                            FPWebViewVC *webViewVC = [FPWebViewVC new];
                            webViewVC.strUrl = webUrl;
                            [self.navigationController pushViewController:webViewVC animated:YES];
                        } else {
                            [MBManager hideLoading];
                            [self showText:msg];
                        }
                    } failure:^(NSError * _Nonnull error) {
                        [MBManager hideLoading];
                        [self showError:error];
                    }];
                }
//                [FPUserInfoModel checkMatchProductsParam:userInfoModel isHome:YES success:^(NSInteger code, NSString * _Nonnull message, FPUserInfoModel *infoModel) {
//                    [MBManager hideLoading];
//                    
//                    if (code == 200) {
//                        
//                        // 未匹配到产品
//                        if (infoModel.succeed == NO) {
//                            
//                            // 更多产品(全部产品)
//                            [self moreProductAction];
//                        }
//                        else {
//                         
//                            FPLoanController *vc = [[FPLoanController alloc] init];
//                            vc.model = self.model;
//                            vc.productsList = infoModel.products;
//                            vc.infoModel = infoModel;
//                            [self.navigationController pushViewController:vc animated:YES];
//                        }
//                    }
//                    else {
//                        
//                        [self showText:message];
//                    }
//                    
//                } failure:^(NSError * _Nonnull error) {
//                    [self showError:error];
//                }];
            }
            else {
                
                [MBManager hideLoading];
                FPAuthenticationController *vc = [[FPAuthenticationController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            }
            
        } failure:^(NSError * _Nonnull error) {
            [self showError:error];
        }];
    }
}

#pragma mark - 精选区 name
- (void)getFeatureName {
    
    [FPHomeModel getFeaturedNameSuccess:^(NSInteger code, NSString * _Nonnull message, NSString * _Nonnull featuredName) {
       
        if (code == 200) {
            
            self.featuredName = featuredName;
            
            [self.tableView reloadData];
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


#pragma mark - banner data
- (void)getBannerData {
    
    [FPHomeBannerModel getBannerListSuccess:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
       
        if (code == 200) {
            
            [self.bannerSource removeAllObjects];
            
            for (FPHomeBannerModel *m in list) {
                
                [self.bannerSource addObject:m];
            }
            [self.tableView reloadData];
        }
        
    } failure:^(NSError * _Nonnull error) {
    }];
}



#pragma mark - 展示数据 年化率/期限等
- (void)rateDataInfo {
    
    // 获取数据展示
    [FPHomeDataModel getHomePageRateDataDisplaySuccess:^(NSInteger dataCode, NSString * _Nonnull dataMessage, NSString *dataInfo) {
        
        if (dataCode == 200) {
            
            self.headerView.rateLab.text = dataInfo;
        }
        
    } failure:^(NSError * _Nonnull dataError) {
    }];
}

#pragma mark - 获取剩余额度
- (void)getData {
    
    [FPHomeModel getHomePageInfoSuccess:^(NSInteger code, NSString * _Nonnull message, FPHomeModel * _Nonnull model) {
        
        if (code == 200) {
            
            self.model = model;
            if (model.dayCredit.longLongValue > 0) {
            
                self.didBorrowed = YES;
                self.headerView.applyBtn.userInteractionEnabled = NO;
                [self.headerView.applyBtn setTitle:@"审核中" forState:(UIControlStateNormal)];
            }
            else {
                
                self.didBorrowed = NO;
                self.headerView.applyBtn.userInteractionEnabled = YES;
                [self.headerView.applyBtn setTitle:@"立即申请" forState:(UIControlStateNormal)];
            }
            
            self.headerView.loanAmountLab.text = formatAmount([NSDecimalNumber decimalNumberWithString:model.totalCredit]);
            self.headerView.applyBtn.hidden = NO;
        }

    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}

#pragma mark - 加载金刚区
- (void)loadCollectionSource {
    
    [FPProductModel getProductsWithType:(FPProductPostType1) success:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
       
        if (code == 200) {
            
            [self.collectionSource removeAllObjects];
            
            for (FPProductModel *model in list) {
                
                [self.collectionSource addObject:model];
            }
            
            [self.tableView reloadData];
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - 加载精选区
- (void)getAdvertData {
    
    [FPProductModel getProductsWithType:(FPProductPostType2) success:^(NSInteger code, NSString * _Nonnull message, NSArray * _Nonnull list) {
        
        if (code == 200) {
            
            [self.productSource removeAllObjects];
            
            for (FPProductModel *model in list) {
                
                [self.productSource addObject:model];
            }
            [self.tableView reloadData];
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


- (void)getUserInfo {
    
    [MBManager showLoading];
    
    [FPUserInfoModel checkUserProfileInfoSuccess:^(NSInteger code, NSString * _Nonnull message, FPUserInfoModel * _Nonnull userInfoModel) {
        [MBManager hideLoading];
        
        if (userInfoModel) {
            
            // 入资状态判断（0未实名，1已实名，2留资1完成，3留资2完成）
            NSInteger statusCode = userInfoModel.status.integerValue;
            
            if (statusCode == 0) {
                
                [self auditStatusNoReview];
            }
            else if (statusCode == 1) {
                
                [self auditStatusInReview];
            }
            else if (statusCode == 2) {
                
                [self auditStatusReviewNoPass];
            }
            // 审核完
            else if (statusCode == 3 || statusCode == 4 || statusCode == 5) {
                
                [self auditStatusReviewSuccess];
            }
        }
        else {
            
            [self notLogin];
//            auditStatusReviewSuccess 留资1和2都完成
//            auditStatusReviewNoPass 留资1完成 未留资2
//            auditStatusInReview 已实名 未留资1
//            auditStatusNoReview  未实名
//            [self auditStatusReviewSuccess];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
    } failure:^(NSError * _Nonnull error) {
        
        [self showError:error];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        [self notLogin];
    }];
    
    [FPUserInfoModel getUserInfoWithSuccess:^(FPUserInfoModel * _Nonnull model) {
        
        
    } failure:^(NSError * _Nonnull error) {
    }];
    
    
    [self getAdvertData];
    [self loadCollectionSource];
}

- (void)setReduceHeaderHeight:(CGFloat)height hideAuthView:(BOOL)hideAuthView {
    
    CGFloat headerHeight;
    
    CGFloat temp = 0.f;
    
    if (hideAuthView) {
        
        temp = 52.f;
    }

    CGFloat bgH = 318.f; // 这个高度是固定的 因为view中的控件之间的距离+高度 不会变更高  //(SCREEN_WIDTH - 32.f) / 343.f * 318.f;  // (imageViewWidth / imageWidth) * imageHeight
//    headerHeight = 80.f + 395.f - 318.f + bgH;// + UIDevice.statusBarHeight;
    
    headerHeight = 475.f - temp;
    
    self.headerView.headerHeight.constant = bgH - height;
    self.headerView.imgHeight.constant = bgH - height;
    
    self.headerView.frame = CGRectMake(0.f , 0.f, SCREEN_WIDTH, headerHeight + UIDevice.statusBarHeight - height);
}

#pragma mark - 留资1和2都完成
- (void)auditStatusReviewSuccess {
    
    [self getData];
    self.headerView.titleTipLab.text = @"预估额度可借（元）";
    self.headerView.loanAmountLab.text = @"200,000";
    self.headerView.applyBtn.hidden = NO;
    [self.headerView.applyBtn setTitle:@"立即申请" forState:(UIControlStateNormal)];
    
    [self setReduceHeaderHeight:80.f hideAuthView:NO];
    
    self.headerView.bottomBackView.hidden = YES;
    
    self.headerView.backViewTopToHeight.constant = 104.f;
    
    self.headerView.authBackView.hidden = NO;
    self.headerView.authTipLab1.text = @"恭喜您成功获得额度";
    self.headerView.authTipLab2.text = @"去借款 >";
}

#pragma mark - 留资1完成 未留资2
- (void)auditStatusReviewNoPass {
    
    self.headerView.titleTipLab.text = @"最高可借（元）";
    self.headerView.loanAmountLab.text = @"200,000";
    self.headerView.applyBtn.hidden = NO;
    [self.headerView.applyBtn setTitle:@"申请额度" forState:(UIControlStateNormal)];
    
    [self setReduceHeaderHeight:0.f hideAuthView:NO];
    
    self.headerView.bottomBackView.hidden = NO;
    
    self.headerView.backViewTopToHeight.constant = 104.f;
    self.headerView.authBackView.hidden = NO;
    
    self.headerView.authTipLab1.text = @"填写资料，即可申请借款";
    self.headerView.authTipLab2.text = @"继续填写 >";
}

#pragma mark - 已实名 未留资1
- (void)auditStatusInReview {
    
    self.headerView.titleTipLab.text = @"最高可借（元）";
    self.headerView.loanAmountLab.text = @"200,000";
    self.headerView.applyBtn.hidden = NO;
    [self.headerView.applyBtn setTitle:@"申请额度" forState:(UIControlStateNormal)];
    
    [self setReduceHeaderHeight:0.f hideAuthView:NO];
    
    self.headerView.bottomBackView.hidden = NO;
    
    self.headerView.backViewTopToHeight.constant = 104.f;
    self.headerView.authBackView.hidden = NO;
    
    self.headerView.authTipLab1.text = @"填写资料，即可申请借款";
    self.headerView.authTipLab2.text = @"去填写 >";
}


#pragma mark - 未实名
- (void)auditStatusNoReview {
    
    self.headerView.titleTipLab.text = @"最高可借（元）";
    self.headerView.loanAmountLab.text = @"200,000";
    self.headerView.applyBtn.hidden = NO;
    [self.headerView.applyBtn setTitle:@"申请额度" forState:(UIControlStateNormal)];
    
    [self setReduceHeaderHeight:0.f hideAuthView:NO];
    
    self.headerView.bottomBackView.hidden = NO;
    
    self.headerView.backViewTopToHeight.constant = 104.f;
    self.headerView.authBackView.hidden = NO;
    
    self.headerView.authTipLab1.text = @"完成认证，即可申请借款额度";
    self.headerView.authTipLab2.text = @"去认证 >";
}

#pragma mark - 未登录UI
- (void)notLogin {
    
    if (FPUserModel.globalToken.length > 1) {
        
        [self auditStatusNoReview];
    }
    else {
     
        self.headerView.titleTipLab.text = @"最高可借（元）";
        self.headerView.applyBtn.hidden = NO;
        self.headerView.loanAmountLab.text = @"200,000";
        [self.headerView.applyBtn setTitle:@"申请额度" forState:(UIControlStateNormal)];
        
        [self setReduceHeaderHeight:0.f hideAuthView:NO];
        
        self.headerView.bottomBackView.hidden = NO;
        
        self.headerView.backViewTopToHeight.constant = 104.f;
        self.headerView.authBackView.hidden = NO;
        
        self.headerView.authTipLab1.text = @"登录后即可获取额度";
        self.headerView.authTipLab2.text = @"立即登录 >";
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
#pragma mark - 产品列表 需要添加一个审核字段
//    FPUserInfoModel *userInfo = FPUserInfoModel.sharedUserInfo;
//    
//    if (FPUserModel.globalToken.length > 0) {
//        
//        if (userInfo.phone.length > 1) {
//            
//            if (self.model.auditStatus.integerValue == 3) {
//                
//                
//            }
//        }
//    }
    if (FPUserModel.globalToken.length > 0) {
        
        return 3 + self.productSource.count;
    }
    else {
     
        return 1;
    }
    
    return 0;
}

- (NSInteger)calculateRowsForItems:(NSInteger)itemCount {
    
    // 每行最多 5 个 item，最多 2 行
    NSInteger rows = (itemCount + 5 - 1) / 5; // 向上取整
    return MIN(rows, 2); // 至多显示 2 行
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat cellHeight = 120.f / 343.f * (SCREEN_WIDTH-32.f);
    
    if (FPUserModel.globalToken.length > 0) {
        
        if (indexPath.row == 0) {
            
            //..  计算个数
            NSInteger count = [self calculateRowsForItems:self.collectionSource.count];
            
            return count * 90.f;
        }
#pragma mark - banner
        else if (indexPath.row == 1) {
            
            if (self.bannerSource.count == 0) {
                
                return 1.f;
            }
            else {
                
                return cellHeight + 16.f;
            }
        }
#pragma mark - product tip cell
        else if (indexPath.row == 2) {
            
            if (self.productSource.count == 0) {
                
                return 1.f;
            }
            else {
             
                return 45.f;
            }
        }
#pragma mark - product
        else {
            
            return 120.f;
        }
    }
    else {
        return cellHeight + 16.f;
    }
    
    return 0.f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FPBannerCell *bannerCell;
    
    if (bannerCell == nil) {
        
        bannerCell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPBannerCell.class) owner:nil options:nil].lastObject;
    }
    
    // 已登录
    if (FPUserModel.globalToken.length > 0) {
        
        // 金刚区
        if (indexPath.row == 0) {
            
            FPHomeCollectionCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"DefaultCell"];
            
            if (!cell) {
                // 如果没有复用的单元格，则创建一个新的
                cell = [[FPHomeCollectionCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FPHomeCollectionCell"];
            }
            
            [cell analysisArray:self.collectionSource];
            
            WeakSelf;
            cell.transmitBlock = ^(NSInteger i) {
                
                FPProductModel *model = weakSelf.collectionSource[i];
//                [weakSelf showText:model.advertId];
                [weakSelf productClick:model];
            };
            
            return cell;
        }
        // banner
        else if (indexPath.row == 1) {
            
            bannerCell.contentView.hidden = self.bannerSource.count == 0 ? YES : NO;
            
            [bannerCell analysisBannerSource:self.bannerSource];
            
            WeakSelf;
            bannerCell.block = ^(NSUInteger index) {
              
                [weakSelf bannerDidSelectAtIndex:index];
            };
            
            return bannerCell;
        }
        // 产品~
        else {
            
            // tip cell
            if (indexPath.row == 2) {
            
                FPHomeProductTipCell *cell;
                
                if (!cell) {
                    
                    cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPHomeProductTipCell.class) owner:nil options:nil].lastObject;
                }
                
                [cell.moreLab addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(moreProductAction)]];
                
                cell.titleLab.text = self.featuredName.length > 0 ? self.featuredName : @"优质精选";
            
                cell.contentView.hidden = self.productSource.count == 0 ? YES : NO;
                
                return cell;
            }
            // product cell
            else {
                    
                FPHomeProductCell *cell;
                
                if (!cell) {
                    
                    cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(FPHomeProductCell.class) owner:nil options:nil].lastObject;
                }
                
                cell.applyBtn.indexPath = indexPath;
                
                if (self.productSource.count > 0) {
                    
                    FPProductModel *model = self.productSource[indexPath.row - 3];
                    
                    [cell analysisUIWithProductModel:model];
                }
                
                return cell;
            }
        }
    }
    // 未登录
    else {
        
        [bannerCell analysisBannerSource:self.bannerSource];
        
        WeakSelf;
        bannerCell.block = ^(NSUInteger index) {
          
            [weakSelf bannerDidSelectAtIndex:index];
        };
        
        return bannerCell;
    }
    
    return nil;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // 防诈骗手册
//    FPManualController *vc = [[FPManualController alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
    
    if (FPUserModel.globalToken.length > 0) {
        
        // 金刚区
        if (indexPath.row == 0) {
            
        }
        // banner
        else if (indexPath.row == 1) {
            
            
        }
        // 产品~
        else {
            
            // tip cell
            if (indexPath.row == 2) {
            }
            // product cell
            else {
                    
                FPProductModel *model = self.productSource[indexPath.row - 3];
                
                [self productClick:model];
            }
        }
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self.tableView || scrollView == self.group_tableView) {
        
        CGFloat offsetY = scrollView.contentOffset.y;
        
        // 最多下滑到table view 的background view的高度
        if (offsetY <= -150.f) {
            
            offsetY = 0.f;
            self.tableView.contentOffset = CGPointMake(0.f, -150.f);
        }
    }
}

- (void)loginInvalidAction {
    
    self.loginInvalidRet = YES;
     
//    [self getData];
//    self.headerView.loanAmountLab.text = @"200,000";
//    self.headerView.applyBtn.hidden = NO;
}

#pragma mark - 登录校验
- (BOOL)userIsLogin {
    
//    FPUserInfoModel *info = FPUserInfoModel.sharedUserInfo;

    BOOL ret = YES;
    
    if (FPUserInfoModel.sharedUserInfo.phone.length < 1) {
        
        ret = NO;
//        [self getProtocolShowLoginView:YES];
        FPLoginController *vc = [[FPLoginController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
    return ret;
}

#pragma mark - 了解众鑫花 查看更多
- (void)aboutUsAction {

    FPAboutUsController *vc = [[FPAboutUsController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 查看更多 产品
- (void)moreProductAction {
    
    FPProductListController *vc = [[FPProductListController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - banner 点击事件
- (void)bannerDidSelectAtIndex:(NSUInteger)index {
    
    if (self.bannerSource.count == 0) {
        // 防诈骗手册
        FPManualController *vc = [[FPManualController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }
    
    FPHomeBannerModel *model = self.bannerSource[index];
    
    if ([model.name isEqualToString:@"金融防诈手册"]) {
     
        // 防诈骗手册
        FPManualController *vc = [[FPManualController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
     
        FPMainWebController *vc = [[FPMainWebController alloc] init];
        
        vc.urlString = model.jumpUrl;
        vc.titleString = model.name;
        
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)productClick:(FPProductModel *)model {
    
    [MBManager showLoading];
    [FPProductModel clickProduct:model success:^(BOOL isSuccess, NSString * _Nonnull URLString) {
        [MBManager hideLoading];
        
        if (isSuccess) {
            
            FPMainWebController *vc = [[FPMainWebController alloc] init];
            
            vc.urlString = URLString;
            vc.titleString = model.productName;
            
            [self.navigationController pushViewController:vc animated:YES];
        }
        else {
            
            [self showText:@"产品已下架"];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self showError:error];
    }];
}
@end
